package com.zzyweb.managementsystem.service.impl;



import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zzyweb.managementsystem.mapper.UserMapper;
import com.zzyweb.managementsystem.pojo.UserInfo;
import com.zzyweb.managementsystem.service.UserService;
import com.zzyweb.managementsystem.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author zhiyi
 * @date 9/22/25
 **/
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Override
    public void logIn(UserInfo userInfo) {
        //hutool md5 加密
        String codedPwd = SecureUtil.md5(userInfo.getPassword());
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userInfo.getUsername())
                        .eq( "password", codedPwd);
        UserInfo userInfo1 = userMapper.selectOne(queryWrapper, true);
        if(userInfo1 == null) {
            throw new RuntimeException("登陆失败，请重新检查登陆信息");
        }
    }

    @Override
    public void verifyCode(String captchaId, String code) {
        //从redis 中拿到 code
        String codeInRedis = redisUtil.get(captchaId);
        if (codeInRedis == null || codeInRedis.trim().isEmpty()) {
            throw new RuntimeException("验证码失效");
        }
        if (!codeInRedis.equalsIgnoreCase(code)) {
            throw new RuntimeException("验证码错误");
        }
    }

    @Override
    public void register(UserInfo userInfo) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userInfo.getUsername());
        if(userMapper.exists(queryWrapper)) {
            throw new RuntimeException("用户名已存在");
        }
        int row = userMapper.insert(userInfo);
        if (row <= 0) {
            throw new RuntimeException("用户注册失败");
        }
    }

    @Override
    public UserInfo getUserByUserName(String username) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        UserInfo userInfo = userMapper.selectOne(queryWrapper);
        if (userInfo == null) {
            throw new RuntimeException("用户名不存在");
        }
        return userInfo;
    }
}
